import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:my_shop/cache_event_identification.dart';
import 'package:my_shop/load_my_goods.dart';
import 'package:my_shop/widget/cart_item.dart';

class CartPage extends StatefulWidget {
  const CartPage({Key? key}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage>
    with SingleTickerProviderStateMixin {
  List<GoodModel> cartList = [];
  List<int> selectedGoodIdList = [];
  bool isEdit = false;

  void refreshData() {
    setState(() {
      cartList = SpUtil.getObjList<GoodModel>(Constant.cartModelList,
              (v) => GoodModel.fromJson(v as Map<String, dynamic>)) ??
          [];
    });
  }

  @override
  void initState() {
    super.initState();
    refreshData();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Cart'),
          actions: [
            GestureDetector(
                onTap: () {
                  setState(() {
                    isEdit = !isEdit;
                  });
                },
                child: Container(
                  padding: const EdgeInsets.only(right: 15),
                  child: isEdit ? const Text('Done') : const Text('Edit'),
                ))
          ],
          backgroundColor: Color(SpUtil.getInt(Constant.mainColor) ?? MyColor.mainColor.value),
        ),
        body: Stack(
          children: [
            EasyRefresh(
              onRefresh: () {
                refreshData();
              },
              child: ListView(
                children: <Widget>[
                  ...List.generate(cartList.length, (index) {
                    return GZXOrderWidget(
                      isEdit: false,
                      orderModel: cartList[index],
                      addTap: (value) {
                        cartList[index].num = cartList[index].num! + 1;
                        SpUtil.putObjectList(Constant.cartModelList, cartList);
                      },
                      removeTap: (value) {
                        cartList[index].num = cartList[index].num! - 1;
                        SpUtil.putObjectList(Constant.cartModelList, cartList);
                      },
                      updateValueChanged: (value) {
                        cartList[index].num =
                            int.tryParse(value) ?? cartList[index].num;
                        SpUtil.putObjectList(Constant.cartModelList, cartList);
                      },
                      onSelectChanged: (model, value) {
                        setState(() {
                          if (!(model.isSelected ?? false)) {
                            selectedGoodIdList.add(model.goodId!);
                          } else {
                            selectedGoodIdList.remove(model.goodId!);
                          }
                          model.isSelected = !(model.isSelected ?? false);
                        });
                      },
                    );
                  }).toList(),
                ],
              ),
            ),
            Positioned(
              bottom: 10,
              right: 10,
              child: TextButton(
                  onPressed: selectedGoodIdList.isNotEmpty
                      ? () {
                          ///Modify the cache of the shopping cart for either deletion or completion
                          ///However, it is also necessary to modify the inventory information
                          /// of the total product list when purchasing
                          if (!isEdit) {
                            Fluttertoast.showToast(msg: 'buy success');
                            List<GoodModel> allGoodsList =
                                SpUtil.getObjList<GoodModel>(
                                        Constant.allGoodsList,
                                        (v) => GoodModel.fromJson(
                                            v as Map<String, dynamic>)) ??
                                    [];
                            for (int i = 0; i < allGoodsList.length; i++) {
                              if (selectedGoodIdList
                                  .contains(allGoodsList[i].goodId)) {
                                allGoodsList[i].stock =
                                    (allGoodsList[i].stock ?? 0) -
                                        (cartList
                                                .firstWhere((element) =>
                                                    element.goodId ==
                                                    allGoodsList[i].goodId)
                                                .num ??
                                            0);
                              }
                            }
                            SpUtil.putObjectList(
                                Constant.allGoodsList, allGoodsList);

                            List<OrderModel> orderList =
                                SpUtil.getObjList<OrderModel>(
                                        Constant.orderList,
                                        (v) => OrderModel.fromJson(
                                            v as Map<String, dynamic>)) ??
                                    [];
                            OrderModel tempModel = OrderModel(
                              orderId: orderList.isEmpty
                                  ? 1
                                  : orderList.last.orderId! + 1,
                              orderNo: orderList.isEmpty
                                  ? '000001'
                                  : getOrderNo(orderList.last.orderNo!),
                              createTime: DateTime.now().toString(),
                              totalPrice: getTotalPrice(selectedGoodIdList),
                              goodList: cartList
                                  .where((element) => selectedGoodIdList
                                      .contains(element.goodId))
                                  .toList(),
                            );
                            if (orderList.isEmpty) {
                              orderList = [tempModel];
                            } else {
                              orderList.add(tempModel);
                            }
                            SpUtil.putObjectList(Constant.orderList, orderList);
                          } else {
                            Fluttertoast.showToast(msg: 'delete success');
                          }

                          cartList.removeWhere((element) =>
                              selectedGoodIdList.contains(element.goodId));
                          for (var model in cartList) {
                            model.isSelected = false;
                          }
                          selectedGoodIdList.clear();
                          SpUtil.putObjectList(
                              Constant.cartModelList, cartList);
                          setState(() {});
                        }
                      : null,
                  style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.resolveWith(
                      (states) {
                        return Colors.white;
                      },
                    ),
                    backgroundColor:
                        MaterialStateProperty.resolveWith((states) {
                      return selectedGoodIdList.isNotEmpty
                          ? isEdit
                              ? Colors.red
                              : const Color(0xFFFF8400)
                          : Colors.grey;
                    }),
                  ),
                  child: isEdit ? const Text('Delete') : const Text('buy')),
            )
          ],
        ),
      ),
    );
  }

  String getOrderNo(String lastNo) {
    int lastNoToInt = int.parse(lastNo) + 1;
    switch (lastNoToInt.toString().length) {
      case 1:
        return '00000$lastNoToInt';
      case 2:
        return '0000$lastNoToInt';
      case 3:
        return '000$lastNoToInt';
      case 4:
        return '00$lastNoToInt';
      case 5:
        return '0$lastNoToInt';
      default:
        return '$lastNoToInt';
    }
  }

  double getTotalPrice(List<int> idList) {
    double total = 0;
    for (int id in idList) {
      total =
          total + cartList.firstWhere((element) => element.goodId == id).price!;
    }
    return total;
  }
}
